#! /usr/bin/python

# 引入GPIO模块
import RPi.GPIO as GPIO
import time

# 指定编码方式 + 关闭警告信息
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# 设置输入, 输出引脚
btn_pin = 1
led_pin = 4

# 初始化 GPIO 模式
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(btn_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# 初始化 LED 灯状态
GPIO.output(led_pin, GPIO.LOW)

# 设置按键的回调函数，当检测到按键按下时执行
def pressed():
    # LED 状态获取
    state = GPIO.input(led_pin)
    # LED 状态取反
    GPIO.output(led_pin, not state)


# 设置按键监控事件
GPIO.add_event_detect(btn_pin, GPIO.RISING, bouncetime=200)

# LED 初始状态是否亮: False
state = False
try:
    while True:
        if GPIO.event_detected(btn_pin):
            state = not state
            GPIO.output(led_pin, state)
            print("led is bright: ", state)
        time.sleep(0.01)
except Exception as e:
    print(e)

# 清理占用的GPIO资源
GPIO.cleanup()